from django.shortcuts import render
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.oauth.utils import generate_sign_openid
from .models import OAuthQQuser
from . import serializers

class OAuthQQLoginView(APIView):
    def get(self,request):
        #1.获取参数
        state = request.query_params.get("state","/")

        #2.创建qq对象
        oauth_qq = OAuthQQ(client_id = settings.QQ_CLIENT_ID,client_secret=settings.QQ_CLIENT_SECRET,redirect_uri=settings.QQ_REDIRECT_URI,state=state)

        #3.返回qq登陆页面
        login_url  = oauth_qq.get_qq_url()
        return Response({"auth_url":login_url})


class OAuthQQUserView(GenericAPIView):
    serializer_class =  serializers.OAuthQQuserSerializer

    def get(self,request):
        #1,获取参数code.校验
        code = request.query_params.get("code")
        if not code:
            return Response("code丢失了")

        #2.根据code获取access_token
        oauth_qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,redirect_uri=settings.QQ_REDIRECT_URI,state="/")

        access_token=  oauth_qq.get_access_token(code)

        #3.根据acces_token获取openid
        openid = oauth_qq.get_open_id(access_token)
        # 4.通过openid查询qq对象用户
        try:
            oauth_qq_user = OAuthQQuser.objects.get(openid=openid)

        except OAuthQQUser.DoesNotExist:
            # 4.1初次授权
            pass
            sgin_openid  =  generate_sign_openid
            return Response({"access_token":sgin_openid})
        else:
            # 5.非初次授权
            user = oauth_qq_user.user

            from rest_framework_jwt.settings import api_settings
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
        return Response({
                    "token":token,
                    "username":username,
                    "user_id":userid
                })


    def post(self,request):
        #1.获取参数
        dict_data = request.data

        #2.创建序列化器
        serializer  = self.get_serializer(data = dict_data)


        #3.校验入库
        serializer.is_valid(raise_exception=True)
        user = serializer.save()


        # 3,1根据用户数据,生成token


        from rest_framework_jwt.settings import api_settings
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        #4.返回响应
        return Response(
            {
                "token" :  token,
                "user_id" : user.id,
                "username" :  user.username,
            }
        )